﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data.EntityClient;
using System.Data;
using UsersProvider.Repositories.RelationalRepositories.Interfaces;

namespace UsersProvider.Repositories.RelationalRepositories
{
    public class ClearRelationalDataRepository: IClearRelationalDataRepository
    {
        /// <summary>
        /// Clears DB data
        /// </summary>
        public void ClearData()
        {
            using (UsersModelEntities context = new UsersModelEntities())
            {
                DbConnection conn = ((EntityConnection)context.Connection).StoreConnection;

                ConnectionState initialState = conn.State;
                try
                {
                    if (initialState != ConnectionState.Open)
                        conn.Open();  // open connection if not already open 

                    using (DbCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "ClearDB";
                        cmd.ExecuteNonQuery();
                    }
                }
                finally
                {
                    if (initialState != ConnectionState.Open)
                        conn.Close(); // only close connection if not initially open 
                }
            }
        }
    }
}
